require 'websocket-client-simple'
require 'redis'
require 'json'
# redis = Redis.new(host: 'alihk', port: 6379)

url = ARGV[0] || 'ws://localhost:8003'
logfile = ARGV[1]

Redis.current = Redis.new(host: 'alihk', port: 6379)

def redis
  Redis.current
end

if logfile
  $stdout.reopen(logfile, 'w')
  $stdout.sync = true
  $stderr.reopen($stdout)
end

ws = WebSocket::Client::Simple.connect(url)

ws.on :message do |msg|
  puts ">> #{msg.data}"
end

ws.on :open do
  puts "-- websocket open (#{ws.url})"
end

ws.on :close do |e|
  puts "-- websocket close (#{e.inspect})"
  exit 1
end

ws.on :error do |e|
  puts "-- error (#{e.inspect})"
end

module BlockChain
  # a class distribute msg to redis
  class Distributor
    def self.distribute(msg)
      return if msg['ch'] != 'market.xrpusdt.bbo'

      tick = msg['tick']
      puts tick
      redis_local = Redis.new
      redis_local.setex('xrpusdt' + tick['seqId'].to_s, 60, tick.to_json)
    end
  end
end

begin
  redis.subscribe(:blockchain, :dat) do |on|
    on.subscribe do |channel, subscriptions|
      puts "Subscribed to ##{channel} (#{subscriptions} subscriptions)"
    end

    on.message do |_channel, message|
      # puts "##{channel}: #{message}"
      data = JSON.parse(message)
      BlockChain::Distributor.distribute(data)
      redis.unsubscribe if message == 'exit'
    end

    on.unsubscribe do |channel, subscriptions|
      puts "Unsubscribed from ##{channel} (#{subscriptions} subscriptions)"
    end
  end
rescue Redis::BaseConnectionError => e
  puts "#{e}, retrying in 1s"
  sleep 1
  retry
end
